<template>
    <view class="container">
        <!-- 搜索框 -->
        <view class="search-header">
            <view class="search-box">
                <view class="search-input-wrap">
                    <uni-icons type="search" size="18" color="#999"></uni-icons>
                    <input type="text" v-model="searchKey" placeholder="搜索文章" placeholder-class="placeholder"
                        confirm-type="search" focus @confirm="handleSearch" />
                    <view v-if="searchKey" class="clear-btn" @tap="clearSearch">
                        <uni-icons type="clear" size="14" color="#999"></uni-icons>
                    </view>
                </view>
                <view class="search-btn" @tap="handleSearch">搜索</view>
            </view>
        </view>

        <!-- 搜索结果 -->
        <view class="search-content">
            <!-- 搜索提示 -->
            <view class="search-tip" v-if="searchKey && !loading && searchResults.length > 0">
                找到相关结果，显示第 {{ page }} 页
            </view>

            <!-- 搜索结果列表 -->
            <view class="article-list" v-if="searchResults.length > 0">
                <view class="article-item" v-for="(article, index) in searchResults" :key="index"
                    @tap="goToDetail(article)">
                    <view class="article-content">
                        <image class="article-image" :src="getPostImage(article)" mode="aspectFill" lazy-load />
                        <view class="article-info">
                            <text class="title">{{ formatTitle(article.title.rendered) }}</text>
                            <rich-text class="desc" :nodes="formatContent(article.excerpt.rendered)"></rich-text>
                            <view class="meta-info">
                                <text class="date">{{ formatDate(article.date) }}</text>
                                <view class="category-tags" v-if="article.categories && article.categories.length">
                                    <text class="category-tag" v-for="(catId, idx) in article.categories" :key="idx"
                                        v-if="getCategoryName(catId)">
                                        {{ getCategoryName(catId) }}
                                    </text>
                                </view>
                            </view>
                            <view class="read-more-btn">
                                <text>阅读全文</text>
                                <uni-icons type="right" size="14" color="#007AFF"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 加载状态 -->
            <view class="loading-box" v-if="loading">
                <view class="loading">
                    <view class="loading-spinner"></view>
                    <text>加载中...</text>
                </view>
            </view>

            <!-- 没有更多 -->
            <view class="no-more" v-if="noMore && searchResults.length > 0">
                <text>没有更多内容了</text>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="!loading && searchResults.length === 0">
                <image src="/static/empty-search.png" mode="aspectFit"></image>
                <text v-if="searchKey" class="empty-text">未找到"{{ searchKey }}"相关内容</text>
                <text v-else class="empty-tip">输入关键词开始搜索</text>
                <view v-if="searchKey" class="suggestion">
                    <text class="suggestion-title">建议您：</text>
                    <text class="suggestion-item">• 检查输入是否正确</text>
                    <text class="suggestion-item">• 尝试其他相关词</text>
                    <text class="suggestion-item">• 使用更简短的关键词</text>
                </view>
            </view>
        </view>

        <!-- 返回顶部按钮 -->
        <view class="back-to-top" v-if="showBackToTop" @tap="backToTop">
            <uni-icons type="top" size="20" color="#fff"></uni-icons>
        </view>
    </view>
</template>
  
<script>
import api from '@/api/wordpress'

export default {
    data() {
        return {
            searchKey: '',
            searchResults: [],
            loading: false,
            page: 1,
            noMore: false,
            defaultImage: 'https://lzphy.top/wp-content/uploads/2024/11/wp_editor_md_ab8de7ba3b3b6cd27c2957f95aab644a.jpg',
            categories: {},
            showBackToTop: false,
            scrollTop: 0
        }
    },
    async onLoad(options) {
        await this.getCategories()

        if (options.keyword) {
            this.searchKey = decodeURIComponent(options.keyword)
            this.handleSearch()
        }
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.refreshList()
    },
    // 触底加载
    onReachBottom() {
        if (!this.loading && !this.noMore) {
            this.page++
            this.handleSearch(false)
        }
    },
    // 添加页面滚动监听
    onPageScroll(e) {
        // 当滚动超过 500px 时显示返回顶部按钮
        this.showBackToTop = e.scrollTop > 500
        this.scrollTop = e.scrollTop
    },
    methods: {
        // 刷新列表
        async refreshList() {
            this.page = 1
            this.noMore = false
            this.searchResults = []
            await this.getCategories()
            await this.handleSearch()
            uni.stopPullDownRefresh()
        },

        // 搜索处理
        async handleSearch(reset = true) {
            const value = this.searchKey.trim()
            if (!value) {
                uni.showToast({
                    title: '请输入搜索内容',
                    icon: 'none'
                })
                return
            }

            if (reset) {
                this.page = 1
                this.noMore = false
                this.searchResults = []
            }

            this.loading = true

            try {
                const res = await api.searchArticles(value, this.page)
                if (res.statusCode === 200) {
                    const newResults = res.data

                    if (this.page === 1) {
                        this.searchResults = newResults
                    } else {
                        this.searchResults = [...this.searchResults, ...newResults]
                    }

                    // 如果返回的结果少于10条，说明没有更多了
                    if (newResults.length < 10) {
                        this.noMore = true
                    }
                }
            } catch (e) {
                console.error('搜索错误:', e)
                uni.showToast({
                    title: '搜索失败',
                    icon: 'none'
                })
            } finally {
                this.loading = false
                uni.hideKeyboard()
            }
        },

        clearSearch() {
            this.searchKey = ''
            this.searchResults = []
        },

        getPostImage(article) {
            return api.getPostImage(article)
        },

        handleImageError(e, index) {
            this.searchResults[index].imageUrl = this.defaultImage
        },

        formatTitle(title) {
            return title.replace(/&#8211;/g, '-')
                .replace(/&amp;/g, '&')
                .replace(/&#8220;/g, '"')
                .replace(/&#8221;/g, '"')
                .replace(/&#8216;/g, "'")
                .replace(/&#8217;/g, "'")
        },

        formatContent(content) {
            return content.replace(/<[^>]+>/g, '')
                .replace(/&nbsp;/g, ' ')
                .replace(/&hellip;/g, '...')
        },

        formatDate(date) {
            const d = new Date(date)
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        },

        goToDetail(article) {
            console.log('点击搜索结果文章ID:', article.id)
            uni.navigateTo({
                url: `/pages/detail/detail?id=${article.id}&title=${encodeURIComponent(article.searchTitle || article.title.rendered)}`
            })
        },

        async getCategories() {
            try {
                const res = await api.getCategories()
                if (res.statusCode === 200 && res.data) {
                    const categoriesObj = {}
                    res.data.forEach(cat => {
                        categoriesObj[cat.id] = cat.name
                    })
                    this.categories = categoriesObj
                }
            } catch (e) {
                console.error('获取分类失败:', e)
            }
        },

        getCategoryName(catId) {
            return this.categories[catId] || ''
        },

        // 添加返回顶部方法
        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300
            })
        }
    }
}
</script>
  
<style>
.container {
    min-height: 100vh;
    background-color: #f5f6fa;
}

/* 搜索头部 */
.search-header {
    background-color: #fff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
    position: sticky;
    top: 0;
    z-index: 100;
}

.search-box {
    display: flex;
    align-items: center;
}

.search-input-wrap {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f6fa;
    padding: 12rpx 24rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
}

.search-input-wrap input {
    flex: 1;
    font-size: 28rpx;
    margin: 0 16rpx;
    height: 60rpx;
}

.clear-btn {
    padding: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.clear-btn:active {
    opacity: 0.7;
}

.search-btn {
    font-size: 28rpx;
    color: #007AFF;
    padding: 20rpx 30rpx;
    background-color: #f5f6fa;
    border-radius: 40rpx;
}

.search-btn:active {
    opacity: 0.7;
}

/* 搜索提示 */
.search-tip {
    font-size: 24rpx;
    color: #999;
    padding: 20rpx 30rpx;
    background: #fff;
    margin-bottom: 20rpx;
}

/* 搜索结果列表 */
.article-list {
    padding: 0 30rpx;
}

.article-item {
    background: #fff;
    border-radius: 20rpx;
    margin-bottom: 30rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.article-item:active {
    transform: scale(0.98);
}

.article-image {
    width: 100%;
    height: 360rpx;
    background-color: #f5f5f5;
}

.article-info {
    padding: 24rpx;
}

.title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.5;
    margin-bottom: 16rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
    margin-bottom: 20rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.article-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20rpx;
    border-top: 1rpx solid #f5f5f5;
}

.date {
    font-size: 24rpx;
    color: #999;
}

.read-more {
    font-size: 24rpx;
    color: #007AFF;
    margin-right: 8rpx;
}

/* 空状态 */
.empty-state {
    padding: 120rpx 60rpx;
    text-align: center;
}

.empty-state image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
}

.empty-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
}

.empty-tip {
    font-size: 28rpx;
    color: #999;
}

.suggestion {
    margin-top: 60rpx;
    text-align: left;
}

.suggestion-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
}

.suggestion-item {
    font-size: 26rpx;
    color: #999;
    line-height: 2;
    display: block;
}

/* 加载状态 */
.loading-box {
    padding: 40rpx 0;
    text-align: center;
}

.loading {
    display: inline-flex;
    align-items: center;
}

.loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #007AFF;
    border-radius: 50%;
    margin-right: 16rpx;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading text {
    font-size: 28rpx;
    color: #999;
}

/* 添加没有更多样式 */
.no-more {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 24rpx;
}

.no-more text {
    position: relative;
    padding: 0 30rpx;
}

.no-more text::before,
.no-more text::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 60rpx;
    height: 1rpx;
    background: #ddd;
}

.no-more text::before {
    left: -60rpx;
}

.no-more text::after {
    right: -60rpx;
}

.article-content {
    display: flex;
    padding: 12px;
}

.article-image {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    object-fit: cover;
}

.article-info {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding: 10px 15px;
}

.meta-info {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
}

.category-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
}

.category-tag {
    font-size: 12px;
    color: #ff5722;
    background-color: rgba(255, 87, 34, 0.1);
    padding: 2px 6px;
    border-radius: 10px;
    white-space: nowrap;
}

.title {
    font-size: 16px;
    font-weight: bold;
    line-height: 1.4;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.desc {
    font-size: 13px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.read-more-btn {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #ff5722;
    font-size: 14px;
}

.read-more-btn text {
    margin-right: 4px;
}

/* 添加返回顶部按钮样式 */
.back-to-top {
    position: fixed;
    right: 20px;
    bottom: 80px;
    width: 40px;
    height: 40px;
    background-color: #ff5722;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(255, 87, 34, 0.3);
    z-index: 999;
    transition: all 0.3s ease;
}

.back-to-top:active {
    transform: scale(0.95);
    background-color: #f4511e;
}
</style> 